<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小程序WebView交互页面</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入微信小程序JSSDK -->
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    
    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#07C160', // 微信绿色
                        secondary: '#1677FF',
                        neutral: '#F5F5F5',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .btn-effect {
                @apply transition-all duration-200 transform active:scale-95;
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <!-- 页面标题 -->
    <header class="bg-white shadow-sm py-4 px-6 border-b border-gray-100">
        <h1 class="text-xl font-semibold text-gray-800">WebView交互演示</h1>
    </header>
    
    <!-- 主要内容 -->
    <main class="flex-1 flex flex-col items-center justify-center p-6 max-w-md mx-auto w-full">
        <div class="w-full bg-white rounded-xl shadow-md p-6 mb-6 transform transition-all duration-300 hover:shadow-lg">
            <!-- 输入区域 -->
            <div class="mb-6">
                <label for="message" class="block text-sm font-medium text-gray-700 mb-2">发送消息给小程序</label>
                <div class="flex gap-3">
                    <input 
                        type="text" 
                        id="message" 
                        class="flex-1 px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                        placeholder="请输入消息内容..."
                    >
                    <button 
                        id="sendBtn" 
                        class="bg-primary text-white px-4 py-2 rounded-lg btn-effect flex items-center justify-center gap-1"
                    >
                        <i class="fa fa-paper-plane"></i>
                        <span>发送</span>
                    </button>
                </div>
            </div>
            
            <!-- 参数输入区域 -->
            <div class="mb-6">
                <label for="params" class="block text-sm font-medium text-gray-700 mb-2">跳转参数</label>
                <input 
                    type="text" 
                    id="params" 
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="请输入跳转参数，例如: id=123&name=test"
                >
            </div>
            
            <!-- 文件上传区域 -->
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">文件上传</label>
                <div class="flex flex-col gap-3">
                    <div class="flex gap-3">
                        <input 
                            type="file" 
                            id="fileInput" 
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                            accept="image/*"
                        >
                        <button 
                            id="uploadBtn" 
                            class="bg-secondary text-white px-4 py-2 rounded-lg btn-effect flex items-center justify-center gap-1"
                        >
                            <i class="fa fa-upload"></i>
                            <span>上传</span>
                        </button>
                    </div>
                    <div id="uploadStatus" class="text-sm text-gray-600 hidden"></div>
                </div>
            </div>
            
            <!-- 按钮区域 -->
            <div class="grid grid-cols-2 gap-4">
                <button 
                    id="closeBtn" 
                    class="bg-gray-200 text-gray-700 px-4 py-3 rounded-lg btn-effect flex items-center justify-center gap-2"
                >
                    <i class="fa fa-times-circle"></i>
                    <span>关闭页面</span>
                </button>
                
                <button 
                    id="navigateBtn" 
                    class="bg-secondary text-white px-4 py-3 rounded-lg btn-effect flex items-center justify-center gap-2"
                >
                    <i class="fa fa-arrow-right"></i>
                    <span>跳转页面</span>
                </button>
            </div>
        </div>
        
        <!-- 状态提示 -->
        <div id="status" class="w-full py-3 px-4 rounded-lg bg-gray-100 text-center text-gray-600 hidden"></div>
    </main>
    
    <!-- 页脚 -->
    <footer class="bg-white py-3 px-6 text-center text-sm text-gray-500 border-t border-gray-100">
        <p>WebView与小程序交互示例</p>
    </footer>

    <script>
        // 等待页面加载完成
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const messageInput = document.getElementById('message');
            const paramsInput = document.getElementById('params');
            const fileInput = document.getElementById('fileInput');
            const uploadBtn = document.getElementById('uploadBtn');
            const uploadStatus = document.getElementById('uploadStatus');
            const sendBtn = document.getElementById('sendBtn');
            const closeBtn = document.getElementById('closeBtn');
            const navigateBtn = document.getElementById('navigateBtn');
            const statusEl = document.getElementById('status');
            
            // 显示状态消息
            function showStatus(element, message, isError = false) {
                element.textContent = message;
                element.classList.remove('hidden', 'text-green-600', 'text-red-600');
                
                if (isError) {
                    element.classList.add('text-red-600');
                } else {
                    element.classList.add('text-green-600');
                }
                
                element.classList.remove('hidden');
                
                // 3秒后隐藏状态消息
                setTimeout(() => {
                    element.classList.add('hidden');
                }, 3000);
            }
            
            // 检查是否在小程序环境中
            function isWechatMiniProgram() {
                return typeof wx !== 'undefined' && wx.miniProgram;
            }
            
            // 发送消息给小程序
            sendBtn.addEventListener('click', function() {
                const message = messageInput.value.trim();
                
                if (!message) {
                    showStatus(statusEl, '请输入消息内容', true);
                    return;
                }
                
                if (isWechatMiniProgram()) {
                    // 通过postMessage向小程序发送消息
                    wx.miniProgram.postMessage({
                        data: {
                            message: message,
                            type: 'user_message'
                        }
                    });
                    
                    showStatus(statusEl, '消息已发送给小程序');
                    messageInput.value = '';
                } else {
                    showStatus(statusEl, '不在小程序环境中，无法发送消息', true);
                }
            });
            
            // 关闭当前页面（返回上一页）
            closeBtn.addEventListener('click', function() {
                if (isWechatMiniProgram()) {
                    wx.miniProgram.navigateBack({
                        delta: 1, // 返回的页面数
                        success: function() {
                            showStatus(statusEl, '正在关闭页面...');
                        },
                        fail: function() {
                            showStatus(statusEl, '关闭页面失败', true);
                        }
                    });
                } else {
                    showStatus(statusEl, '不在小程序环境中，无法关闭页面', true);
                }
            });
            
            // 跳转到小程序特定页面
            navigateBtn.addEventListener('click', function() {
                if (isWechatMiniProgram()) {
                    // 获取参数输入
                    const params = paramsInput.value.trim();
                    let url = '/package-other/health/web?from=webview';
                    
                    // 如果有参数，则添加到URL中
                    if (params) {
                        // 确保参数格式正确
                        const separator = url.includes('?') ? '&' : '?';
                        url += separator + params;
                    } else {
                        // 添加一个随机数参数作为示例
                        url += '&n=' + Math.floor(Math.random() * 1000);
                    }
                    
                    // 跳转到小程序的特定页面
                    wx.miniProgram.navigateTo({
                        url: url,
                        success: function() {
                            showStatus(statusEl, '正在跳转到目标页面...');
                        },
                        fail: function() {
                            showStatus(statusEl, '跳转失败', true);
                        }
                    });
                } else {
                    showStatus(statusEl, '不在小程序环境中，无法跳转页面', true);
                }
            });
            
            // 文件上传功能
            uploadBtn.addEventListener('click', function() {
                const file = fileInput.files[0];
                
                if (!file) {
                    showStatus(uploadStatus, '请选择要上传的文件', true);
                    return;
                }
                
                // 检查文件大小（限制为5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showStatus(uploadStatus, '文件大小不能超过5MB', true);
                    return;
                }
                
                // 检查文件类型
                if (!file.type.startsWith('image/')) {
                    showStatus(uploadStatus, '只能上传图片文件', true);
                    return;
                }
                
                if (isWechatMiniProgram()) {
                    // 在小程序环境中，通过postMessage将文件信息发送给小程序
                    // 小程序端需要实现相应的文件处理逻辑
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        wx.miniProgram.postMessage({
                            data: {
                                type: 'file_upload',
                                fileName: file.name,
                                fileType: file.type,
                                fileSize: file.size,
                                fileData: e.target.result // base64数据
                            }
                        });
                        showStatus(uploadStatus, '文件信息已发送给小程序，请在小程序端完成上传');
                    };
                    reader.readAsDataURL(file);
                } else {
                    // 在H5环境中，使用标准的FormData上传
                    showStatus(uploadStatus, '正在上传文件...');
                    
                    const formData = new FormData();
                    formData.append('file', file);
                    // 添加其他需要的字段
                    formData.append('uploadType', 'h5');
                    
                    // 这里需要替换为你的实际上传接口
                    fetch('https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        }
                        throw new Error('Upload failed');
                    })
                    .then(data => {
                        showStatus(uploadStatus, '文件上传成功');
                        console.log('Upload success:', data);
                    })
                    .catch(error => {
                        showStatus(uploadStatus, '文件上传失败: ' + error.message, true);
                        console.error('Upload error:', error);
                    });
                }
            });
            
            // 输入框回车发送
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendBtn.click();
                }
            });
            
            // 初始化检查
            if (isWechatMiniProgram()) {
                showStatus(statusEl, '已连接到小程序');
            } else {
                showStatus(statusEl, '未检测到小程序环境');
            }
        });
    </script>
</body>
</html>